<?php
class CategorySaveEditAction extends AdminAction
{
	public function __construct()
	{
		parent::__construct();
		$this->responseType = 'json';
	}
	
	protected function afterConstruct()
	{
		$this->parseDtds('category','edit');
	}
	
	public function execute()
	{
		$id				= $this->context->post('oid');
		$data			= $this->getValidData();
		
		$categoryService		= new CategoryService();
		//检查上级类目和当前类目ID的关系
		if(!$categoryService->checkIdAndPid($data['id'],$data['pid']))
		{
			$this->data['error_messages']['pid']	= array('error'=>'上级类目不能是当前类目或者它的子类目');
		}
		//检查新添加的类目是否已经存在
		if(!is_numeric($id) || $id<=0)
		{
			$tmp	= $categoryService->get($data['id']);
			if($tmp)
			{
				$this->data['error_messages']['id']	= array('error'=>'该ID的类目已经存在');
			}
		}
		if(empty($this->data['error_messages']))
		{
			if(is_numeric($id) && $id>0)
			{
				$categoryService->update($id,$data);
				$this->code	= 200;
				$this->data['forward'] = C('LtUrl')->generate('Category', 'Index');
			}
			else
			{
				$id	= $categoryService->add($data);
				if($id)
				{
					$this->code	= 200;
					$this->data['forward'] = C('LtUrl')->generate('Category', 'Index');
				}
				else
				{
					$this->code	= 400;
				}
			}
		}
		else
		{
			$this->code	= 400;
		}
	}
}
